import api from '../../api';
import type { Department, DepartmentMember, DepartmentForm } from '../../../types/rbac';

/**
 * 部门列表查询参数（对应后端SysDepartmentQuery）
 */
export interface DepartmentListParams {
  current?: number;
  size?: number;
  name?: string;
  code?: string;
  status?: number; // 1-启用，0-禁用
  parentId?: string | number;
  keyword?: string;
  orderBy?: string;
  orderType?: 'asc' | 'desc';
}

/**
 * 部门列表响应类型（对应后端分页响应）
 */
export interface DepartmentListResponse {
  records: Department[];
  total: number;
  size: number;
  current: number;
  pages: number;
  hasPrevious: boolean;
  hasNext: boolean;
}

/**
 * 部门成员查询参数
 */
export interface DepartmentMemberParams {
  current?: number;
  size?: number;
  keyword?: string;
  roleId?: string;
  status?: number;
}

/**
 * 部门成员响应类型
 */
export interface DepartmentMemberResponse {
  records: DepartmentMember[];
  total: number;
  size: number;
  current: number;
  pages: number;
  hasPrevious: boolean;
  hasNext: boolean;
}

/**
 * 部门管理API服务
 * 注意：通过网关调用v3-system服务，路径需要以/system开头
 */
export const departmentApi = {
  /**
   * 获取部门列表（分页）
   * 后端接口：POST /api/v3/sys/departments/page
   */
  getDepartments: async (params?: DepartmentListParams): Promise<DepartmentListResponse> => {
    const requestData = {
      current: params?.current || 1,
      size: params?.size || 10,
      name: params?.name,
      code: params?.code,
      status: params?.status,
      parentId: params?.parentId,
      keyword: params?.keyword,
      orderBy: params?.orderBy || 'sort',
      orderType: params?.orderType || 'asc',
      ...params
    };

    return api.post('/system/api/v3/sys/departments/page', requestData);
  },

  /**
   * 获取部门树结构
   * 后端接口：GET /api/v3/sys/departments/tree
   */
  getDepartmentTree: async (params?: {
    parentId?: number;
    status?: number;
    includeDisabled?: boolean;
  }): Promise<Department[]> => {
    const queryParams: any = {};
    
    if (params?.parentId !== undefined) {
      queryParams.parentId = params.parentId;
    }
    if (params?.status !== undefined) {
      queryParams.status = params.status;
    }
    if (params?.includeDisabled !== undefined) {
      queryParams.includeDisabled = params.includeDisabled;
    }

    return api.get('/system/api/v3/sys/departments/tree', { params: queryParams });
  },

  /**
   * 获取部门详情
   * 后端接口：GET /api/v3/sys/departments/get/{id}
   */
  getDepartment: async (id: string | number): Promise<Department> => {
    return api.get(`/system/api/v3/sys/departments/get/${id}`);
  },

  /**
   * 创建部门
   * 后端接口：POST /api/v3/sys/departments/add
   */
  createDepartment: async (data: DepartmentForm): Promise<Department> => {
    // 转换前端数据格式到后端格式
    const dto = {
      name: data.name,
      code: data.code,
      parentId: data.parentId || null,
      managerId: data.managerId || null,
      sort: data.sort || 1,
      status: data.status || 1,
      description: data.description || '',
      phone: data.phone,
      email: data.email
      // 角色相关字段已移除
    };

    return api.post('/system/api/v3/sys/departments/add', dto);
  },

  /**
   * 更新部门
   * 后端接口：PUT /api/v3/sys/departments/update
   */
  updateDepartment: async (id: string | number, data: Partial<DepartmentForm>): Promise<Department> => {
    // 转换前端数据格式到后端格式
    const dto = {
      id: id,
      name: data.name,
      code: data.code,
      parentId: data.parentId,
      managerId: data.managerId,
      sort: data.sort,
      status: data.status,
      description: data.description,
      phone: data.phone,
      email: data.email
      // 角色相关字段已移除
    };

    return api.put('/system/api/v3/sys/departments/update', dto);
  },

  /**
   * 删除部门
   * 后端接口：DELETE /api/v3/sys/departments/delete/{id}
   */
  deleteDepartment: async (id: string | number): Promise<void> => {
    return api.delete(`/system/api/v3/sys/departments/delete/${id}`);
  },

  /**
   * 批量删除部门
   * 后端接口：DELETE /api/v3/sys/departments (批量删除需要确认后端是否支持)
   */
  batchDeleteDepartments: async (ids: (string | number)[]): Promise<void> => {
    return api.delete('/system/api/v3/sys/departments', { data: { ids } });
  },

  /**
   * 获取部门成员列表
   * 后端接口：POST /api/v3/sys/departments/members
   */
  getDepartmentMembers: async (
    departmentId: string | number, 
    params?: DepartmentMemberParams
  ): Promise<DepartmentMemberResponse> => {
    const requestData = {
      departmentId: departmentId,
      current: params?.current || 1,
      size: params?.size || 10,
      keyword: params?.keyword,
      roleId: params?.roleId,
      status: params?.status,
      ...params
    };

    return api.post('/system/api/v3/sys/departments/members', requestData);
  },

  /**
   * 添加部门成员
   * 后端接口：POST /api/v3/sys/departments/member/add
   */
  addDepartmentMember: async (departmentId: string | number, userIds: (string | number)[]): Promise<void> => {
    return api.post('/system/api/v3/sys/departments/member/add', {
      departmentId,
      userIds
    });
  },

  /**
   * 移除部门成员
   * 后端接口：POST /api/v3/sys/departments/member/remove
   */
  removeDepartmentMember: async (departmentId: string | number, userId: string | number): Promise<void> => {
    return api.post('/system/api/v3/sys/departments/member/remove', {
      departmentId,
      userId
    });
  },

  /**
   * 批量移除部门成员
   * 后端接口：DELETE /api/v3/sys/departments/{departmentId}/members (批量删除)
   */
  batchRemoveDepartmentMembers: async (departmentId: string | number, userIds: (string | number)[]): Promise<void> => {
    return api.delete(`/system/api/v3/sys/departments/${departmentId}/members`, { data: { userIds } });
  },

  /**
   * 设置部门负责人
   * 后端接口：POST /api/v3/sys/departments/manager/set
   */
  setDepartmentLeader: async (departmentId: string | number, userId: string | number): Promise<void> => {
    return api.post('/system/api/v3/sys/departments/manager/set', {
      departmentId,
      userId
    });
  },

  /**
   * 取消部门负责人
   * 后端接口：DELETE /api/v3/sys/departments/{departmentId}/manager
   */
  removeDepartmentLeader: async (departmentId: string | number, userId: string | number): Promise<void> => {
    return api.delete(`/system/api/v3/sys/departments/${departmentId}/manager`, { data: { userId } });
  },

  /**
   * 移动部门（调整父级部门）
   * 后端接口：POST /api/v3/sys/departments/move
   */
  moveDepartment: async (id: string | number, newParentId: string | number | null): Promise<void> => {
    return api.post('/system/api/v3/sys/departments/move', {
      departmentId: id,
      newParentId
    });
  },

  /**
   * 调整部门排序
   * 后端接口：PUT /api/v3/sys/departments/{id}/sort (需要确认后端是否有此接口)
   */
  updateDepartmentSort: async (id: string | number, sort: number): Promise<void> => {
    return api.put(`/system/api/v3/sys/departments/${id}/sort`, {
      sort
    });
  },

  /**
   * 启用部门
   * 后端接口：PUT /api/v3/sys/departments/{id}/enable
   */
  enableDepartment: async (id: string | number): Promise<void> => {
    return api.put(`/system/api/v3/sys/departments/${id}/enable`);
  },

  /**
   * 禁用部门
   * 后端接口：PUT /api/v3/sys/departments/{id}/disable
   */
  disableDepartment: async (id: string | number): Promise<void> => {
    return api.put(`/system/api/v3/sys/departments/${id}/disable`);
  },

  /**
   * 启用/禁用部门（兼容旧方法）
   * 后端接口：PUT /api/v3/sys/departments/{id}/enable 或 /api/v3/sys/departments/{id}/disable
   */
  toggleDepartmentStatus: async (id: string | number, status: number): Promise<void> => {
    const endpoint = status === 1 ? 'enable' : 'disable';
    return api.put(`/system/api/v3/sys/departments/${id}/${endpoint}`);
  },

  /**
   * 获取部门统计信息
   * 后端接口：GET /api/v3/sys/departments/stats (需要确认后端是否有此接口)
   */
  getDepartmentStats: async (departmentId?: string | number) => {
    const params = departmentId ? { departmentId } : {};
    return api.get('/system/api/v3/sys/departments/stats', { params });
  },

  /**
   * 导出部门数据
   * 后端接口：POST /api/v3/sys/departments/export (需要确认后端是否有此接口)
   */
  exportDepartments: async (params?: DepartmentListParams) => {
    return api.post('/system/api/v3/sys/departments/export', params, {
      responseType: 'blob'
    });
  },

  /**
   * 检查部门编码是否存在
   * 后端接口：GET /api/v3/sys/departments/check-code
   */
  checkDepartmentCode: async (code: string, excludeId?: string): Promise<boolean> => {
    const params = { code, excludeId };
    return api.get('/system/api/v3/sys/departments/check-code', { params });
  },

  /**
   * 获取部门管理员用户列表
   */
  getDepartmentManagers: async (): Promise<any[]> => {
    const response = await api.get('/system/api/v3/sys/departments/managers');
    // 确保返回正确的数据格式
    return Array.isArray(response) ? response : (response?.data || []);
  }
};